//
//  OAuthViewController.swift
//  开心微博
//
//  Created by 郑开心 on 15/12/8.
//  Copyright © 2015年 郑开心. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class OAuthViewController: UIViewController,UIWebViewDelegate {

    private let clientId = "3745717972"
    private let appSecret="c4d0a2dcaf0367bdf32261ce1eb5110b"
    private let redirectUrl = "https://www.baidu.com"
    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = UIWebView(frame: self.view.bounds)
        self.view.addSubview(webView)
        
        var baseUrlStr = "https://api.weibo.com/oauth2/authorize"
        
        
        baseUrlStr += "?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
        //NSLog(baseUrlStr)
        let url = NSURL(string: baseUrlStr)
        
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        webView.delegate = self
    }
    
    // MARK : 拦截请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = NSString(string: (request.URL?.absoluteString)!)
        let rang = urlStr.rangeOfString("code=")
        
        if rang.length > 0 {
            let code = urlStr.substringFromIndex(rang.location+rang.length)
            
            accessTokenWithCode(code)
            return false
        }
        
        return true
    }
    
    func accessTokenWithCode(code: String){
        var params = ["client_id":clientId,"client_secret":appSecret]
        params["grant_type"] = "authorization_code"
        params["code"] = code
        params["redirect_uri"] = redirectUrl
        
        Alamofire.request(.POST, "https://api.weibo.com/oauth2/access_token", parameters: params)
            .responseJSON() { response in
                switch response.result {
                case .Success:
                    if let value = response.result.value {
                        
                        let json = JSON(value)
                        let account = Account(json: json)
                        AccountTool.saveAccount(account)
                        RootTool.chooseRootViewController(Coant.keyWindow)
                    }
                case .Failure(let error):
                    debugPrint(error)
                }
        }
    
    }
    
    
    
    // MARK : 加载框
    func webViewDidStartLoad(webView: UIWebView) {
        MBProgressHUD.showMessage("正在加载中。。。")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        MBProgressHUD.hideHUD()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        MBProgressHUD.hideHUD()
    }
}
